package cn.csc.module.order.service.item;

import cn.csc.framework.common.pojo.PageResult;
import cn.csc.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.csc.framework.mybatis.core.util.MyBatisUtils;
import cn.csc.module.order.api.item.dto.OrderItemRespDTO;
import cn.csc.module.order.controller.admin.item.vo.*;
import cn.csc.module.order.controller.admin.order.vo.OrderReqVO;
import cn.csc.module.order.controller.admin.order.vo.OrderUpdateDeliveryReqVO;
import cn.csc.module.order.controller.app.order.vo.AppOrderItemCreateReqVO;
import cn.csc.module.order.controller.app.vo.OrderItemReqVO;
import cn.csc.module.order.convert.item.OrderItemConvert;
import cn.csc.module.order.dal.dataobject.addr.OrderAddrDO;
import cn.csc.module.order.dal.dataobject.item.OrderItemDO;
import cn.csc.module.order.dal.dataobject.order.OrderDO;
import cn.csc.module.order.dal.mysql.item.OrderItemMapper;
import cn.csc.module.order.dal.mysql.order.OrderMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.csc.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csc.module.order.enums.ErrorCodeConstants.ORDER_ITEM_NOT_EXISTS;

/**
 * 订单项 Service 实现类
 *
 * @author liuchuang
 */
@Service
@Validated
@Slf4j
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper,OrderItemDO> implements OrderItemService {

    @Resource
    private OrderMapper orderMapper;

    @Override
    public BigInteger createItem(OrderItemCreateReqVO createReqVO) {
        // 插入
        OrderItemDO item = OrderItemConvert.INSTANCE.convert(createReqVO);
        baseMapper.insert(item);
        // 返回
        return item.getId();
    }

    @Override
    public void updateItem(OrderItemUpdateReqVO updateReqVO) {
        // 校验存在
        validateItemExists(updateReqVO.getId());
        // 更新
        OrderItemDO updateObj = OrderItemConvert.INSTANCE.convert(updateReqVO);
        baseMapper.updateById(updateObj);

    }

    @Override
    public void deleteItem(BigInteger id) {
        // 校验存在
        validateItemExists(id);
        // 删除
        baseMapper.deleteById(id);
    }

    private void validateItemExists(BigInteger id) {
        if (baseMapper.selectById(id) == null) {
            throw exception(ORDER_ITEM_NOT_EXISTS);
        }
    }

    @Override
    public OrderItemDO getItem(BigInteger id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<OrderItemDO> getItemList(Collection<BigInteger> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<OrderItemDO> getItemPage(OrderItemPageReqVO pageReqVO) {
        return baseMapper.selectPage(pageReqVO);
    }

    @Override
    public List<OrderItemDO> getItemList(OrderItemExportReqVO exportReqVO) {
        return baseMapper.selectList(exportReqVO);
    }

    @Override
    public  List<OrderItemDO> getItemByOrderId(BigInteger orderId) {
        return baseMapper.selectList("order_id",orderId);
    }

    @Override
    public List<BigInteger> getItemByUserId(BigInteger userId,BigInteger orderId) {
        return baseMapper.getItemByUserId(userId,orderId);
    }

    @Override
    public List<OrderItemDO> getItemByUserIdAndShopId(BigInteger userId, BigInteger shopId) {
        return baseMapper.getItemByUserIdAndShopId(userId,shopId);
    }

    @Override
    public List<OrderItemDO> getByOrderIdAndShopId(BigInteger orderId,BigInteger shopId) {
        return baseMapper.getByOrderIdAndShopId(orderId,shopId);
    }

    @Override
    public OrderItemDO getItemOne(OrderItemReqVO reqVO) {
        return baseMapper.getItemOne(reqVO);
    }

    @Override
    public void updateBatch(List<OrderUpdateDeliveryReqVO> updateReqVO) {
        baseMapper.updateBatch(OrderItemConvert.INSTANCE.convertDOList(updateReqVO),updateReqVO.size());
    }

    @Override
    public void updateOrderStatus(List<BigInteger> orderIds, Integer orderStatus) {
        baseMapper.updateOrderState(orderIds,orderStatus);
    }

    @Override
    public List<BigInteger> getShopIdByOrderId(BigInteger orderId) {
        return baseMapper.getShopIdByOrderId(orderId);
    }

    @Override
    public List<OrderItemDO> getItemByUserIdAndShopIdAndOrderId(BigInteger userId, BigInteger shopId, BigInteger orderId) {
        return baseMapper.getItemByUserIdAndShopIdAndOrderId(userId,shopId,orderId);
    }

    @Override
    public List<OrderItemDO> getListByDeliveryTime(OrderReqVO orderReqVO) {
        return baseMapper.selectList(orderReqVO);
    }

    @Override
    public Integer updateOrderStatus(OrderItemDO orderItemDO) {
        return  baseMapper.updateById(orderItemDO);
    }


    @Override
    public PageResult<OrderWithItemPageRespVO> selectOrderItemsPage(OrderWithItemPageReqVO pageReqVO) {
        log.info("[OrderServiceImpl][selectOrderItemsPage][pageReqVO]=={}", pageReqVO);
        //查询用户的所有订单，分页
        IPage<OrderWithItemPageRespVO> mpPage = MyBatisUtils.buildPage(pageReqVO);
        baseMapper.selectOrderItemsPage(pageReqVO, mpPage);
        long totalPage;
        if (mpPage.getTotal() > 0) {
            if (mpPage.getTotal() % pageReqVO.getPageSize() <= 0)
                totalPage = mpPage.getTotal() / pageReqVO.getPageSize();
            else
                totalPage = (mpPage.getTotal() / pageReqVO.getPageSize()) + 1;
        } else {
            return new PageResult<>();
        }

        return new PageResult<>(mpPage.getRecords(), mpPage.getTotal(), totalPage);
    }

    @Override
    public List<OrderItemDO> getItemList(OrderItemReqVO reqVO) {
        return baseMapper.selectList(reqVO);
    }

    @Override
    public Integer updateByToPaySuccess(List<BigInteger> orderIds) {
        List<OrderDO> orderDOList=orderMapper.selectToPaySuccess(orderIds);
        if(orderDOList==null)
            return null;

        return baseMapper.updateByToPaySuccess(orderDOList.stream().map(OrderDO::getId).collect(Collectors.toList()));
    }

    @Override
    public List<OrderItemBaseVO> getExportList(OrderWithItemPageReqVO pageVO) {
        return baseMapper.getExportList(pageVO);
    }

    @Override
    public List<OrderItemDO> getItemListByOrderId(List<BigInteger> orderIds,Integer orderStatus,BigInteger shopId) {
        return baseMapper.selectList(new LambdaQueryWrapperX<OrderItemDO>()
                .eqIfPresent(OrderItemDO::getShopId, shopId)
                .apply(" ( CASE when "+orderStatus+"=4 then order_status <4  ELSE  order_status ="+orderStatus+" end )")
                .in(OrderItemDO::getOrderId, orderIds));
    }

    @Override
    public List<OrderItemDO> getItemListByOrderId(List<BigInteger> orderIds) {
        return baseMapper.selectList(new LambdaQueryWrapperX<OrderItemDO>()
                .in(OrderItemDO::getOrderId, orderIds));
    }

    @Override
    public Boolean updateByCardPayAmount(List<AppOrderItemCreateReqVO> appOrderItemCreateReqVOs) {
        return baseMapper.updateBatch(OrderItemConvert.INSTANCE.convertDOList02(appOrderItemCreateReqVOs) ,appOrderItemCreateReqVOs.size());
    }

    @Override
    public Map<BigInteger, List<OrderItemRespDTO>> getItemByOrderIds(List<BigInteger> orderIds) {
        List<OrderItemDO> list= baseMapper.selectListByOrderIds(orderIds);
        List<OrderItemRespDTO> dtoList=OrderItemConvert.INSTANCE.convertList03(list);
        return dtoList.stream().collect(Collectors.groupingBy(OrderItemRespDTO::getOrderId));
    }


}
